package com.example.springbootwebdemo.controller;

import com.example.springbootwebdemo.entity.Product;
import com.example.springbootwebdemo.entity.User;
import com.example.springbootwebdemo.repository.ProductRepository;
import com.example.springbootwebdemo.repository.UsersRepository;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Resource
    private UsersRepository usersRepository;

    @Resource
    private ProductRepository productRepository;


    /**
     * 通过controller来访问前端页面
     *
     * @return
     */
    @RequestMapping("/test")
    public String test() {
        return "login";
    }

    /**
     * 将login.html作为首页 不推荐使用
     *
     * @return
     */
//    @RequestMapping("/")
//    public String test1(){
//        return "login";
//    }

    @RequestMapping("/user/login")
    public String login(User user, ModelMap modelMap, HttpSession session) {
        modelMap.addAttribute("username", user.getUsername());
        if (usersRepository.login(user) >= 1) {
            session.setAttribute("userInfo", user);
            //重定向
            return "redirect:/user/list";
        } else {
            modelMap.addAttribute("login_error", "用户名密码错误");
            return "login.html";
        }
    }

    @RequestMapping("/user/list")
    public String findAll(ModelMap modelMap, HttpSession session) {
        User user = (User) session.getAttribute("userInfo");
        List<Product> products = productRepository.findByUsername(user.getUsername());
        modelMap.addAttribute("list", products);
        return "list.html";
    }
}
